#Get start time.
$starttime = localtime;

#Gather pvalues and chomp out new lines into an array. 
open(PVALUES, "PVALUES.TXT");
@pvalues = <PVALUES>;
chomp @pvalues;
$currentquestion = 1;

#Iterator through each line to get pvalues for particular question.
foreach(@pvalues)
{	
	#Load up pvalues to use in script.
	@currentpvalues = split(/\,/,$_);
	$p0 = $currentpvalues[0];
	$p1 = $currentpvalues[1];
	$p2 = $currentpvalues[2];
	$p3 = $currentpvalues[3];
	$p4 = $currentpvalues[4];	
	
	#clear out results database.
	$resultsfile = "SCTL-RESULT-FILES\\results-sctl.csv";
	open (results, ">resultsfile");
	close(results);
	
	#Run algorithm for various class sizes.
	for($n = 6; $n <= 15; $n++)
	{
		#clear out the script
		$scriptfile = "script";
		open (FH, ">$scriptfile");
		close(FH);
		
		#create script and write to file
		open(FH, ">>$scriptfile");
		$script = " interface(prettyprint=0); n:=".$n.";p0:=".$p0.";p1:=".$p1.";p2:=".$p2.";p3:=".$p3.";p4:=".$p4."; simplify(expand((p0+p1*exp(t/n)+p2*exp((2*t)/n)+p3*exp((3*t)/n)+p4*exp((4*t)/n))^n));";
		print FH $script;
		close(FH);
		
		#run script
		$output = `..\\cmaple.exe -q $scriptfile`;
					
		#clean up results
		$output =~s/n := [0-9]\n//g;
		$output =~s/n := [0-9][0-9]\n//g;
		$output =~s/p[0-9] :=.*\n//g;
		$output =~s/\A[0-9]\n//g;
		$output =~s/\(//g;
		$output =~s/\)//g;
		$output =~s/\\//g;
		$output =~s/expt/exp1/g;		
		$output =~s/\n//g;		
		$output =~s/\s//g;
		
						
		#split results
		@splitoutput = split(/\+/, $output);
				
		#save results to file
		open(results, ">>$resultsfile");
		foreach(@splitoutput)
		{
			print results "Q" . $currentquestion . "," . "N" . $n . ",";
			$_ =~s/\*t//g;			
			if($_ =~ m/\*exp/)
			{
				$_ =~s/\*exp/\,/g;
				#print $_ . "\n";
				print results $_. "\n";
			}
			else
			{
				#print $_ . ",0\n";
				print  results $_ . ",0\n";
			}
		}		
		close(results);
	};
	print "Finished Question " . $currentquestion . "\n";
	$currentquestion++;	
}

#Get finish time
$finishtime = localtime;

#Print time results
print "Program Start Time: " . $starttime;
print "\n";
print "Program Finish Time: " . $finishtime;
print "\n";
print "Program Completed.";
exit 1;